home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: NEwbie: How to return a multi-dimensional array from function?
- Date: 8 Mar 96 15:23:49 GMT
- Organization: Clemson University
- Message-ID: <mjs.826298629@hubcap>
- References: <4hp273$8bu@news.xs4all.nl> <31404CE9.1A4A@mc.net>
- NNTP-Posting-Host: hubcap.clemson.edu
- X-Newsreader: NN version 6.5.0 #1
-
- Sean Park <spark@mc.net> writes:
-
- >Anthony Moendir wrote:
- >>
- >> I want to return a multidimensional array fro a function,
- >> something like this:
- >>
- >> char *Foo();
- >>
- >> int main()
- >> {
- >> char tmp[10][5];
- >>
- >> tmp=Foo();
- >> }
- >>
- >> char *Foo()
- >> {
- >> char tmp[10][5];
-
- Two things: (1) If you are going to use the value of tmp outside of Foo(),
- then you need to declare
-
- static tmp[10][5];
-
- Otherwise the storage may disappear when you return from Foo().
-
- >> //do something
- >> return(tmp);
- ^ ^ Parentheses not required here.
- >> }
-
- (2) When you use tmp in an expression, the compiler replaces the array
- name with a constant pointer to its first element. (Among other
- consequences, this means that arrays can't appear on the left side of
- assignments.) In this case, the first element has type
- array-of-15-chars, so a pointer to it is a
- pointer-to-array-of-15-chars. That's the type that the function
- should return, and the type of the variable that you assign it to.
- Thus, Foo() needs to be declared
-
- char (*Foo())[5];
-
- and the tmp in main() should be
-
- char (*tmp)[5];
-
- >> How should i do that?
- >>
- >> Any help would be appreciated
- >> Anthony
-
- Another technique for getting the result back is to pass the array in as an
- argument, as is done below (with corrections).
-
- >You could pass the pointer to the array to the function. That way the
- >function itself will fill your array addresses rather than returning
- >redundant data. You might try:
-
- >void foo(char *tmp);
- ^^^^^^^^^ Here, tmp should be declared char (*tmp)[5].
- >int main()
- >{
- > char tmp[10][5];
- > foo(tmp);
- > return 0;
- >}
- >void foo(char *tmp)
- ^^^^^^^^^ Here, tmp should be declared char (*tmp)[5].
- >{
- >/* You can reference tmp within this function as an array of what ever
- > * dimensions you want. */
- >/* do something */
-
- > return;
- >}
-
- >HTH
-
- >Sean Park
- >spark@mc.net
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-